#
# "@(#) $Id: human.py,v 1.1.1.1 2006-07-27 03:16:08 gioshe Exp $"
#
# This work is released under the GNU GPL, version 2 or later.
#
import time
from kdeemul import i18n
from utils import *

#
# provides human-readable representations of certain types of data
# suitable for display - time, durations, file sizes, etc
#

def humanTimeStamp(obj):
	if obj:
		# convert to local civil time
		if time.localtime()[-1]:
			t = time.localtime(time.mktime(obj)-time.altzone)
		else:
			t = time.localtime(time.mktime(obj)-time.timezone)
		return time.strftime("%m/%d/%y %I:%M %p",t)
	return ""

def humanBitRate(obj,short=False):
	if obj:
		if short:
			return "%d kbps" % (obj/1000.0)
		else:
			return "%.1f kbps" % (obj/1000.0)
	return ""

def humanSampleRate(obj):
	if obj:
		return ("%.3f" % (obj/1000.0))+" kHz"
	return ""

def humanFileSize(obj):
	if obj:
		if obj>=1024*1024*1024:
			return ("%.2f" % (obj/(1024*1024*1024.0))) +" GB"
		if obj>=1024*1024:
			return ("%.2f" % (obj/(1024*1024.0)))+" MB"
		elif obj>=1024:
			return ("%.2f" % (obj/1024.0))+" KB"
		else:
			return str(obj)+" bytes"
	return ""

def humanComma(obj):
	if obj:
		result = ""
		while obj>=1000:
			if len(result)>0: result = "%03d,%s" % (obj % 1000,result)
			else: result = "%03d" % (obj % 1000)
			obj = obj/1000
		if len(result)>0: result = "%d,%s" % (obj % 1000,result)
		else: result = "%d" % (obj % 1000)
		return result
		
			
def humanDuration(obj):
	if obj:
		secs = obj/1000
		weeks,secs = divmod(secs,3600*24*7)
		days,secs = divmod(secs,3600*24)
		hours,secs = divmod(secs,3600)
		mins,secs = divmod(secs,60)
		if weeks:
			if weeks==1:
				if days==1: return unikode(i18n("1 week, 1 day"))
				else: return unikode(i18n("1 week, %d days")) % days
			else:
				if days==1:  return unikode(i18n("%d weeks, 1 day")) % weeks
				else: return unikode(i18n("%d weeks, %d days")) % (weeks,days)
		elif days>1:
			return unikode(i18n("%d days")) % days
		elif hours or days:
			return "%d:%02d:%02d" % (days*24+hours,mins,secs)
		else:
			return "%d:%02d" % (mins,secs)
	return ""

if __name__ == '__main__':
	print humanBitRate(48000)
	print humanBitRate(44100)
	print humanBitRate(128000)
	print humanFileSize(0)
	print humanFileSize(768)
	print humanFileSize(1024)
	print humanFileSize(1536)
	print humanFileSize(65536)
	print humanFileSize(1024*1024)
	print humanFileSize(1536*1024)
	print humanFileSize(1024*1024*1024)
	print humanDuration(0)
	print humanDuration(30*1000)
	print humanDuration(60*1000)
	print humanDuration(90*1000)
	print humanDuration(60*60*1000)
	print humanDuration((90*60+5)*1000)
	print humanDuration(24*60*60*1000)
	print humanDuration(((36*60+15)*60+21)*1000)
	print humanDuration(72*60*60*1000)
	print humanDuration(15*24*60*60*1000)
	print humanComma(123456789)
	print humanComma(1234)
	print humanComma(12)
